package com.ideaction.service;

import com.ideaction.entity.version.ClientVersion;
import com.ideaction.globalconst.ParamKey;
import com.ideaction.req.PlayerCommonReqBody;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class VersionService {
    
    @Autowired
    private MongoTemplate funcMongoTemplate;
    
    public ClientVersion versionUp(PlayerCommonReqBody playerCommonReqBody, String ip) {
        List<ClientVersion> clientVersionList = funcMongoTemplate.findAll(ClientVersion.class);
        Iterator<ClientVersion> itr = clientVersionList.iterator();
        // 玩家channel
        String playerChannel = playerCommonReqBody.getParam(ParamKey.CHANNEL);
        // 玩家version
        String playerVersion = playerCommonReqBody.getParam(ParamKey.VERSION);
        while (itr.hasNext()) {
            ClientVersion clientVersion = itr.next();
            String cChannel = clientVersion.getChannel();
            String cVersion = clientVersion.getVersion();
            List<String> ipList = clientVersion.getWhiteIpList();
            // 先找是否有指定版本更新
            if (clientVersion.isSpecialUp()) {
                boolean findSpecial = true;
                // 匹配渠道
                findSpecial &= (StringUtils.isEmpty(cChannel) || cChannel.equals(playerChannel));
                // 匹配版本
                findSpecial &= (StringUtils.isEmpty(cVersion) || cVersion.equals(playerVersion));
                // 匹配白名单
                findSpecial &= (ipList.isEmpty() || ipList.contains(ip));
                // 全部通过则为true,任意一项没通过则为false
                if (findSpecial) {
                    return clientVersion;
                }
                // 如果都没有匹配到指定更新的,则移除此条信息,后面进行通用版本更新判断
                itr.remove();
            }
        }
        // 通用版本更新判断
        List<ClientVersion> list = clientVersionList.stream()
                .filter(e -> e.canPareVersion(playerChannel, playerVersion, ip)).collect(Collectors.toList());
        if (list.size() == 0) {
            return null;
        }
        // 如果有更新版本,则更新,如果热更个强更同时存在,则只会到强更版本(万一有多个存在,找版本最大的)
        Optional<ClientVersion> option = list.stream().sorted().filter(e -> e.getUpType() == 1).findFirst();
        if (option.isPresent()) {
            return option.get();
        } else {
            // 只有热更，则直接到热更
            return option.orElse(list.stream().sorted().filter(e -> e.getUpType() == 2).findFirst().get());
        }
    }
}
